# job/consumers.py

import json
import logging
from asgiref.sync import async_to_sync, sync_to_async
from channels.generic.websocket import AsyncWebsocketConsumer
from channels.layers import get_channel_layer

logger = logging.getLogger(__name__)

class ScreeningResultConsumer(AsyncWebsocketConsumer):
    """
    WebSocket 消费者：用于简历初筛结果的自动推送
    HR 端可接收职位下所有通过的简历评估结果
    求职者端仅接收自己的初筛结果（仅推送通过的）
    """
    async def connect(self):
        """
        建立连接时加入对应职位或用户的分组
        URL 示例：
        - HR 端: /ws/screening/hr/<jobposting_id>/
        - 求职者端: /ws/screening/user/<user_id>/
        """
        # 从 URL 中提取分组类型和 ID
        self.group_type = self.scope['url_route']['kwargs']['group_type']
        self.group_id = self.scope['url_route']['kwargs']['group_id']

        # 构建分组名称
        self.group_name = f"{self.group_type}_{self.group_id}"

        # 加入分组
        await self.channel_layer.group_add(
            self.group_name,
            self.channel_name
        )
        await self.accept()

        logger.info(f"WebSocket 连接建立，加入分组: {self.group_name}")

    async def disconnect(self, close_code):
        """断开连接时退出分组"""
        await self.channel_layer.group_discard(
            self.group_name,
            self.channel_name
        )
        logger.info(f"WebSocket 连接断开，退出分组: {self.group_name}")


    async def screening_result(self, event):
        """
        接收初筛结果事件并转发给前端
        示例 event 数据：
        {
            "type": "screening_result",
            "deliverjob_id": 123,
            "evaluation": {
                "score": 4.5,
                "match_points": ["技能匹配", "学历匹配"],
                "risk_points": ["无工作经验"]
            }
        }
        """
        evaluation = event.get("evaluation")
        score = evaluation.get("score_info", {}).get("score", 0)
        if score >= 0.5:
            # 将评估结果发送给客户端
            await self.send(text_data=json.dumps({
                "type": "screening_result",
                "deliverjob_id": event["deliverjob_id"],
                "evaluation": event["evaluation"]
            }))




# 获取 channel_layer 实例
channel_layer = get_channel_layer()

def send_to_group(group_name, message):
    """
    向指定 Channel Group 广播消息
    :param group_name: 分组名称，如 hr_123 或 user_456
    :param message: 要发送的消息体
    """
    async_to_sync(channel_layer.group_send)(group_name, message)


# 推送hr
def push_screening_result_to_hr(jobposting_id, deliverjob_id, evaluation_text):
    """
    向 HR 分组推送初筛结果
    """
    group_name = f"hr_{jobposting_id}"
    send_to_group(group_name, {
        "type": "screening_result",
        "deliverjob_id": deliverjob_id,
        "evaluation": evaluation_text
    })

# 推送给user
def push_screening_result_to_user(user_id, evaluation_text):
    """
    向求职者推送初筛结果
    """
    group_name = f"user_{user_id}"
    send_to_group(group_name, {
        "type": "screening_result",
        "evaluation": evaluation_text
    })
